package top.mcwebsite.playandroid.business.tixi.impl.ui

import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.LineBreak
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import coil.compose.AsyncImage
import top.mcwebsite.lib.route.api.EasyRouter
import top.mcwebsite.lib.router.annotation.Param
import top.mcwebsite.lib.router.annotation.Route
import top.mcwebsite.playandroid.business.articles.api.model.ArticleModel
import top.mcwebsite.playandroid.business.tixi.impl.vm.ArticleListViewModel
import top.mcwebsite.playandroid.common.constant.RouteConfig
import top.mcwebsite.playandroid.common.constant.RouteConfig.ArticleList
import top.mcwebsite.playandroid.lib.common.ext.encodeURL
import top.mcwebsite.playandroid.strings.Str

@Route("${ArticleList.PATH}?cid={${ArticleList.Param.CID}}&title={${ArticleList.Param.TITLE}}")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ArticleListPage(
    @Param("cid") cid: Long,
    @Param("title") title: String,
) {
    val viewModel: ArticleListViewModel = viewModel()
    LaunchedEffect(Unit) {
        viewModel.cid = cid
    }
    viewModel.HandleUiEffect {
        when (it) {
            is ArticleListUiEffect.GoArticleDetailPageUiEffect -> {
                EasyRouter.navigate("${RouteConfig.ArticleDetail.PATH}/${it.articleModel.link.encodeURL()}")
            }
        }
    }
    val lazyPagingItems = viewModel.pagerFlow.collectAsLazyPagingItems()
    Scaffold(
        topBar = {
            TopAppBar(
                navigationIcon = {
                    IconButton(onClick = {
                        EasyRouter.popBackStack()
                    }) {
                        Icon(Icons.Default.ArrowBack, contentDescription = stringResource(id = Str.back))
                    }
                },
                title = {
                        Text(text = title)
                },
            )
        }
    ) { innerPadding ->
        LazyColumn(
            modifier = Modifier.padding(innerPadding)
        ) {
            if (lazyPagingItems.loadState.refresh == LoadState.Loading) {
                item {
                    Column(
                        modifier = Modifier.fillMaxHeight()
                    ) {
                    }
                }
            }

            items(count = lazyPagingItems.itemCount) { index ->
                lazyPagingItems[index]?.let {
                    ArticleItemContent(model = it, onClick = {
                        viewModel.sendIntent(ArticleListIntent.GoArticleDetailPageIntent(it))
                    })
                    if (index < lazyPagingItems.itemCount - 1) {
                        Divider(
                            modifier = Modifier.padding(horizontal = 12.dp, vertical = 5.dp)
                        )
                    }
                }
            }

            if (lazyPagingItems.loadState.append == LoadState.Loading) {
                item {
                    CircularProgressIndicator(
                        modifier = Modifier
                            .fillMaxWidth()
                            .wrapContentWidth(Alignment.CenterHorizontally)
                    )
                }
            }
        }
    }

}

@Composable
fun ArticleItemContent(model: ArticleModel, onClick: (ArticleModel) -> Unit) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp)
            .padding(top = 16.dp)
            .clickable {
                onClick(model)
            }
    ) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            if (model.author.isNotEmpty()) {
                Text(text = "作者: ", style = MaterialTheme.typography.titleSmall)
                Text(text = model.author, style = MaterialTheme.typography.titleSmall)

            } else if (model.shareUser.isNotBlank()) {
                Text(text = "分享人: ", style = MaterialTheme.typography.titleSmall)
                Text(text = model.shareUser, style = MaterialTheme.typography.titleSmall)
            }
            if (model.tags.isNotEmpty()) {
                Spacer(modifier = Modifier.width(5.dp))
                Box(
                    modifier = Modifier
                        .border(
                            width = 1.dp,
                            color = MaterialTheme.colorScheme.primary,
                            shape = MaterialTheme.shapes.small
                        )
                        .padding(horizontal = 5.dp, vertical = 2.dp),
                    contentAlignment = Alignment.Center,
                ) {
                    Text(
                        text = model.tags.first().name,
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.primary
                    )
                }
            }
            Spacer(modifier = Modifier.weight(1f))
            Text(
                text = model.niceDate,
                style = MaterialTheme.typography.labelMedium
            )
        }
        Spacer(modifier = Modifier.height(5.dp))
        Row {
            Column(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxHeight()
            ) {
                Text(
                    text = model.title,
                    style = MaterialTheme.typography.titleMedium.copy(lineBreak = LineBreak.Simple)
                )
                if (model.desc.isNotBlank()) {
                    Text(
                        text = model.desc,
                        style = MaterialTheme.typography.bodyMedium,
                        maxLines = 3,
                        overflow = TextOverflow.Ellipsis,
                        color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.56f)
                    )
                }
            }
            if (model.envelopPic.isNotBlank()) {
                Spacer(modifier = Modifier.width(5.dp))
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.fillMaxHeight()
                ) {
                    AsyncImage(
                        model = "https://www.wanandroid.com/blogimgs/e87da438-8890-4e62-b889-69cff6c9dee1.png",
                        contentDescription = null,
                        modifier = Modifier.size(70.dp),
                        contentScale = ContentScale.Crop
                    )
                }
            }
        }
        Row(
            modifier = Modifier.padding(vertical = 5.dp)
        ) {
            Text(text = model.superChapterName, style = MaterialTheme.typography.labelMedium)
            Spacer(modifier = Modifier.width(5.dp))
            Text(text = model.chapterName, style = MaterialTheme.typography.labelMedium)
        }
        Spacer(modifier = Modifier.height(16.dp))
    }
}